package com.qire.manhua.model.viewModel.impl;

import android.app.Activity;
import android.view.View;
import android.widget.BaseAdapter;

import com.qire.antsrouter.lifecycleHandler.ActivityManageHandler;
import com.qire.common.basic.ObjectUtil;
import com.qire.common.concurrent.IntervalRunWrapper;
import com.qire.common.concurrent.ThreadUtil;
import com.qire.common.constant.CustomEvent;
import com.qire.common.support.base.BaseViewModel;
import com.qire.common.support.base.IViewModel;
import com.qire.common.utils.NoticeEventBus;
import com.qire.common.widget.adapter.auto.AutoVariable;
import com.qire.common.widget.adapter.auto.SummerBindAdapter;
import com.qire.common.widget.adapter.auto.annotation.AdapterEntityBind;
import com.qire.manhua.BR;
import com.qire.manhua.R;
import com.qire.manhua.controller.BuyCoinsMarketDialogController;
import com.qire.manhua.dal.service.BuyCoinsMarketDialogService;
import com.qire.manhua.databinding.LayoutBuyCoinsMarketDialogItemBinding;
import com.qire.manhua.dialog.BuyResultTipsDialog;
import com.qire.manhua.dialog.SpecialEventDialog;
import com.qire.manhua.model.entity.MarketInfo;
import com.qire.manhua.model.entity.MarketInfo.WaresEntity;
import com.qire.manhua.model.entity.OrderEntity;
import com.qire.manhua.model.enumeration.PaymentMethod;

import java.util.ArrayList;
import java.util.concurrent.TimeUnit;

import androidx.databinding.BaseObservable;
import androidx.databinding.Bindable;
import androidx.lifecycle.MutableLiveData;

public class BuyCoinsMarketDialogViewModel extends BaseViewModel implements IViewModel {

    private BuyCoinsMarketDialogService coinsMarketDialogService = new BuyCoinsMarketDialogService(this);

    /** 充值选项列表 */
    private final ArrayList<WaresItemViewModel> waresItemList = new ArrayList<>();
    private final SummerBindAdapter marketAdapter = new SummerBindAdapter(waresItemList);

    private WaresItemViewModel newcomerWaresItem = null;

    /** 营销市场信息：商品信息 */
    public MarketInfo marketInfo;

    /** 当前选择的商品信息 */
    private WaresItemViewModel selectedWaresViewModel;

    private int comicId;

    @Override
    public int getVariableId() {
        return BR.buyCoinsMarketDialogViewModel;
    }

    //region    #附加管理 begin
    public void onAddition(int comicId, BuyCoinsMarketDialogController controller) {
        this.comicId = comicId;
        marketAdapter.setEventProcess(controller);
    }

    @Override
    protected void onCleared() {
        super.onCleared();
        marketAdapter.setEventProcess(null);
        coinsMarketDialogService = null;
    }
    //endregion #附加管理 end

    //region    #业务数据 begin
    private void toggleSelectItem(WaresItemViewModel waresItemViewModel) {
        if(ObjectUtil.nonNull(selectedWaresViewModel)) {
            selectedWaresViewModel.isSelect = false;
            selectedWaresViewModel.notifyChange();
        }

        if(selectedWaresViewModel != waresItemViewModel) {
            waresItemViewModel.isSelect = true;
            waresItemViewModel.notifyChange();
            selectedWaresViewModel = waresItemViewModel;
        } else {
            selectedWaresViewModel = null;
        }
    }

    public WaresEntity selectedWares() {
        return ObjectUtil.isNull(selectedWaresViewModel) ? null : selectedWaresViewModel.waresEntity;
    }

    public void loadMarketInfo() {
        coinsMarketDialogService.loadMarketInfo();
    }

    public void loadMarketInfo(MarketInfo marketInfo) {
        this.marketInfo = marketInfo;
        waresItemList.clear();

        for(WaresEntity waresEntity : marketInfo.waresEntityList) {
            waresItemList.add(new WaresItemViewModel(waresEntity.setProductId(OrderEntity.章节解锁)));
        }
        marketAdapter.notifyDataSetChanged();
        waresItemList.get(0).toggle();

        WaresEntity newcomerWares = marketInfo.getNewcomerWares();
        if(newcomerWares != null){
            newcomerWaresItem = new WaresItemViewModel(newcomerWares.setProductId(OrderEntity.新人礼包));
            newcomerWaresItem.toggle();
        }

        showNewcomerWares();
    }

    public void createOrder(PaymentMethod paymentMethod, String fromPayActivity) {
        if(ObjectUtil.nonNull(selectedWaresViewModel)) {
//            showDialog("请稍候...");
            coinsMarketDialogService.createOrder(selectedWaresViewModel.buildOrderEntity(), paymentMethod, fromPayActivity);
        }
    }

    public void noticeNewcomerRewardIfNeed() {
        if(ObjectUtil.nonNull(newcomerWaresItem)) {
            NoticeEventBus.NOTICE.sendEvent(CustomEvent.USED_NEWCOMER_REWARD);
        }
    }
    //endregion #业务数据 end


    //endregion #UI操作 end
    public void showNewcomerWares() {
        set("newcomerWaresPanelVisible", newcomerWaresItem == null ? View.GONE : View.VISIBLE);
        set("newcomerWares", newcomerWaresItem);
        set("failureState", marketInfo == null ? false : !marketInfo.countdownIsOver());
        set("failureCountdown", marketInfo == null ? "" : marketInfo.calculateCountdown());

        if (!marketInfo.countdownIsOver()) {
            final IntervalRunWrapper wrapper = ThreadUtil.interval(1, TimeUnit.SECONDS);
            wrapper.andThen(v -> {
                if (marketInfo.countdownIsOver()) {
                    wrapper.stop();
                    return;
                }
                put("failureState", marketInfo == null ? false : !marketInfo.countdownIsOver());
                put("failureCountdown", marketInfo == null ? "" : marketInfo.calculateCountdown());
            }).accept();
        }
    }

    public void showBuyResult(int orderCoin, int awardBean) {
        Activity currentActivity = ActivityManageHandler.HANDLER.currentActivity();
        BuyResultTipsDialog tipsDialog = new BuyResultTipsDialog(currentActivity, BuyResultTipsDialog.PayTipType.Recharge);
        tipsDialog.setOnDismissListener(dialog -> currentActivity.finish());
        tipsDialog.setWare(orderCoin, awardBean)
                .show();
    }

    public void showSpecialEvent(String imgUrl, String pageUrl) {
        Activity previousActivity = ActivityManageHandler.HANDLER.previousActivity();
        new SpecialEventDialog(previousActivity)
                .setImagePath(imgUrl)
                .setEventInfo(pageUrl, "").show();
    }
    //region    #UI操作 begin

    //region    #UI绑定 begin
    public MutableLiveData<Integer> getNewcomerWaresPanelVisible() {
        return get("newcomerWaresPanelVisible");
    }

    public MutableLiveData<Boolean> getFailureState() {
        return get("failureState");
    }

    public MutableLiveData<CharSequence> getFailureCountdown() {
        return get("failureCountdown");
    }

    public MutableLiveData<WaresItemViewModel> getNewcomerWares() {
        return get("newcomerWares");
    }

    public BaseAdapter getMarketAdapter() {
        return marketAdapter;
    }
    //endregion #UI绑定 end

    @AdapterEntityBind(viewRid = R.layout.layout_buy_coins_market_dialog_item)
    public class WaresItemViewModel extends BaseObservable implements AutoVariable<LayoutBuyCoinsMarketDialogItemBinding> {

        private final WaresEntity waresEntity;
        private boolean isSelect = false;

        public WaresItemViewModel(WaresEntity waresEntity) {
            this.waresEntity = waresEntity;
        }

        @Override
        public void bindVariable(LayoutBuyCoinsMarketDialogItemBinding viewBind) {
            viewBind.setWaresItemViewModel(this);
        }

        public void toggle() {
            toggleSelectItem(this);
        }

        public OrderEntity buildOrderEntity() {
            return waresEntity.buildOrderEntity(comicId);
        }

        @Bindable
        public boolean getChecked() {
            return isSelect;
        }

        @Bindable
        public CharSequence getWaresFee() {
            return waresEntity.fee + "元";
        }

        @Bindable
        public String getWaresFeeTextColor() {
            return isSelect ? "#ff9204" : "#131313";
        }

        @Bindable
        public CharSequence getWaresDescribe() {
            return waresEntity.getDescribe();
        }

        @Bindable
        public int getWaresRewardFeeVisible() {
            return waresEntity.rewardFee > 0 ? View.VISIBLE : View.GONE;
        }
        @Bindable
        public CharSequence getWaresRewardFee() {
            return waresEntity.rewardFee > 0 ? "送" + waresEntity.getRewardRate() + "%" : "";
        }
        @Bindable
        public String getWaresRewardFeeTextColor() {
            return isSelect ? "#ff9204" : "#ffffff";
        }

        @Bindable
        public int getFirstPayBuoyVisible() {
            if(waresEntity.rewardFee <= 0) {
                return View.GONE;
            }
            return marketInfo.isFirstPay ? View.VISIBLE : View.GONE;
        }


    }
}
